package com.example.haoqisystem.Utils;
import com.example.haoqisystem.Utils.WaterMarkUtil;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;


public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static String uploadFile(String rootPath, String relativePath, MultipartFile file, String prefix) {
        try {
            String type = getFileTypeByStream(file.getBytes());
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            String now = df.format(new Date());
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String name = (StringUtil.isNullOrEmpty(prefix) ? "" : prefix) + uuid + (StringUtil.isNullOrEmpty(type) ? "" : "." + type);
            String relativeDir = relativePath + "/" + now + "/";
            String dir = rootPath + relativeDir;
            String filepath = dir + name;
            File dirfile = new File(dir);
            if (!dirfile.exists()) { //目录不存在，则创建相应的目录
                dirfile.mkdirs();
            }
            System.out.println(type);

            //插入水印
            assert type != null;
            if (isImageByStream(file.getInputStream())) {
                WaterMarkUtil.markImageByIO("浩奇员工培训系统", file.getInputStream(), Files.newOutputStream(Paths.get(filepath)), 15, type);
            }else {
                FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(Paths.get(filepath)));
            }

//            FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(Paths.get(filepath)));
            return filepath;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    public static void uploadTemplate(String path,String fileName,MultipartFile file) {
        try {
            File dirfile = new File(path);
            System.out.println(dirfile);
            String filepath = path + fileName;
            if (!dirfile.exists()) { //目录不存在，则创建相应的目录
                dirfile.mkdirs();
            }
            FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(Paths.get(filepath)));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }




    public static void downFile(String filePath, String newname, HttpServletResponse response) {
        File file = new File(filePath);
        if (newname == null || newname.equals("")) {
            newname = filePath.substring(filePath.lastIndexOf("/") + 1);
        }
        if (file.exists()) {
            try {
                Path path = Paths.get(filePath);
                String contentType = Files.probeContentType(path);
                FileInputStream fis = new FileInputStream(file);//服务器文件路径
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(newname.getBytes("gbk"), "ISO-8859-1"));
                response.addHeader("Content-Length", "" + file.length());
                response.addHeader("Connection", "Keep-Alive");
                response.addHeader("Cache-Control", "max-age=31536000000");
                response.setContentType(contentType); //设置返回的文件类型
                OutputStream output = response.getOutputStream(); //得到向客户端输出二进制数据的对象
                BufferedInputStream bis = new BufferedInputStream(fis);//输入缓冲流
                BufferedOutputStream bos = new BufferedOutputStream(output);//输出缓冲流

                byte data[] = new byte[4096];//缓冲字节数

                int size = 0;
                size = bis.read(data);
                while (size != -1) {
                    bos.write(data, 0, size);
                    size = bis.read(data);
                }
                bis.close();
                bos.flush();//清空输出缓冲流
                bos.close();
                output.close();
            } catch (IOException e) {
                logger.error("文件下载失败:" + filePath);
            }
        } else {
            logger.error("文件不存在或者已被删除:" + filePath);
        }
    }

    private static final ResourceLoader resourceLoader = new DefaultResourceLoader();

    public static void getImage(String filePath, HttpServletResponse response) {
        Resource resource = resourceLoader.getResource("file:" + filePath);
        if (resource.exists()) {
            try {
                Path path = Paths.get(filePath);
                String contentType = Files.probeContentType(path);

                InputStream fis = resource.getInputStream(); // 通过 Resource 获取图片内容

                response.addHeader("Content-Disposition", "inline;filename=" + resource.getFilename());
                response.addHeader("Content-Length", "" + resource.contentLength());
                response.addHeader("Connection", "Keep-Alive");
                response.addHeader("Cache-Control", "max-age=31536000000");
                response.setContentType(contentType);

                OutputStream output = response.getOutputStream();
                BufferedInputStream bis = new BufferedInputStream(fis);
                BufferedOutputStream bos = new BufferedOutputStream(output);

                byte data[] = new byte[4096];
                int size;
                while ((size = bis.read(data)) != -1) {
                    bos.write(data, 0, size);
                }

                bis.close();
                bos.flush();
                bos.close();
                output.close();
            } catch (IOException e) {
                // 处理异常
                e.printStackTrace();
            }
        } else {
            // 文件不存在
            // 返回错误状态或处理方式
        }
    }




    public static String fileToBase64(File file) throws Exception {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        return org.apache.commons.codec.binary.Base64.encodeBase64String(file2byte(file));// 返回Base64编码过的字节数组字符串
    }

    public static byte[] base64ToByte(String base64) {
        return org.apache.commons.codec.binary.Base64.decodeBase64(base64);
    }

    public static byte[] file2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();

    static {
        getAllFileType();  //初始化文件类型信息
    }

    /**
     * <p>Discription:[getAllFileType,常见文件头信息]</p>
     */
    private static void getAllFileType() {
        FILE_TYPE_MAP.put("jpg", "FFD8FF"); //JPEG (jpg)
        FILE_TYPE_MAP.put("png", "89504E47");  //PNG (png)
        FILE_TYPE_MAP.put("gif", "47494638");  //GIF (gif)
        FILE_TYPE_MAP.put("tif", "49492A00");  //TIFF (tif)
        FILE_TYPE_MAP.put("bmp", "424D"); //Windows Bitmap (bmp)
        FILE_TYPE_MAP.put("dwg", "41433130"); //CAD (dwg)
        FILE_TYPE_MAP.put("html", "68746D6C3E");  //HTML (html)
        FILE_TYPE_MAP.put("rtf", "7B5C727466");  //Rich Text Format (rtf)
        FILE_TYPE_MAP.put("xml", "3C3F786D6C");
        FILE_TYPE_MAP.put("zip", "504B0304");
        FILE_TYPE_MAP.put("rar", "52617221");
        FILE_TYPE_MAP.put("psd", "38425053");  //Photoshop (psd)
        FILE_TYPE_MAP.put("eml", "44656C69766572792D646174653A");  //Email [thorough only] (eml)
        FILE_TYPE_MAP.put("dbx", "CFAD12FEC5FD746F");  //Outlook Express (dbx)
        FILE_TYPE_MAP.put("pst", "2142444E");  //Outlook (pst)
        FILE_TYPE_MAP.put("xls", "D0CF11E0");  //MS Word
        FILE_TYPE_MAP.put("doc", "D0CF11E0");  //MS Excel 注意：word 和 excel的文件头一样
        FILE_TYPE_MAP.put("mdb", "5374616E64617264204A");  //MS Access (mdb)
        FILE_TYPE_MAP.put("wpd", "FF575043"); //WordPerfect (wpd)
        FILE_TYPE_MAP.put("eps", "252150532D41646F6265");
        FILE_TYPE_MAP.put("ps", "252150532D41646F6265");
        FILE_TYPE_MAP.put("pdf", "255044462D312E");  //Adobe Acrobat (pdf)
        FILE_TYPE_MAP.put("qdf", "AC9EBD8F");  //Quicken (qdf)
        FILE_TYPE_MAP.put("pwl", "E3828596");  //Windows Password (pwl)
        FILE_TYPE_MAP.put("wav", "57415645");  //Wave (wav)
        FILE_TYPE_MAP.put("avi", "41564920");
        FILE_TYPE_MAP.put("ram", "2E7261FD");  //Real Audio (ram)
        FILE_TYPE_MAP.put("rm", "2E524D46");  //Real Media (rm)
        FILE_TYPE_MAP.put("mpg", "000001BA");  //
        FILE_TYPE_MAP.put("mov", "6D6F6F76");  //Quicktime (mov)
        FILE_TYPE_MAP.put("asf", "3026B2758E66CF11"); //Windows Media (asf)
        FILE_TYPE_MAP.put("mid", "4D546864");  //MIDI (mid)
        FILE_TYPE_MAP.put("ico", "00000100010010100000010020006804");
    }

    public final static String getImageFileType(File f) {
        if (isImage(f)) {
            try {
                ImageInputStream iis = ImageIO.createImageInputStream(f);
                Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
                if (!iter.hasNext()) {
                    return null;
                }
                ImageReader reader = iter.next();
                iis.close();
                return reader.getFormatName();
            } catch (IOException e) {
                return null;
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 压缩图片
     *
     * @param f     图片
     * @param scale 压缩质量，在0-1之间，
     * @return
     * @throws IOException
     */
    public static byte[] compress(File f, double scale) {
        if (f == null) {
            return null;
        }
        if (scale <= 0) {
            scale = 0.1;
        }
        String type = FileUtil.getImageFileType(f);
        BufferedImage bufferImg;
        try {
            bufferImg = ImageIO.read(f);
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            try {
                if (scale < 1) {
                    int _width = (int) (scale * bufferImg.getWidth());
                    int _height = (int) (scale * bufferImg.getHeight());
                    Image img = bufferImg.getScaledInstance(_width, _height, Image.SCALE_DEFAULT);

                    BufferedImage image = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_RGB);
                    //获取画笔
                    Graphics2D graphics = image.createGraphics();
                    //将Image对象画在画布上,最后一个参数,ImageObserver:接收有关 Image 信息通知的异步更新接口,没用到直接传空
                    graphics.drawImage(img, 0, 0, Color.WHITE, null);
                    //释放资源
                    graphics.dispose();
                    //使用ImageIO的方法进行输出,记得关闭资源
                    ImageIO.write(image, type, byteArrayOut);
                } else {
                    ImageIO.write(bufferImg, type, byteArrayOut);
                }
                return byteArrayOut.toByteArray();
            } finally {
                byteArrayOut.flush();
                byteArrayOut.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("图片压缩失败！");
        }
    }

    public final static String getFileByFile(File file) {
        if (file == null) {
            return null;
        }
        String filetype = null;
        byte[] b = new byte[50];
        try {
            InputStream is = new FileInputStream(file);
            is.read(b);
            filetype = getFileTypeByStream(b);
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filetype;
    }

    public final static String getFileTypeByStream(byte[] b) {
        String filetypeHex = java.lang.String.valueOf(getFileHexString(b));
        Iterator<Map.Entry<String, String>> entryiterator = FILE_TYPE_MAP.entrySet().iterator();
        while (entryiterator.hasNext()) {
            Map.Entry<String, String> entry = entryiterator.next();
            String fileTypeHexValue = entry.getValue();
            if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
                return entry.getKey();
            }
        }
        return null;
    }

    public static final boolean isImage(File file) {
        boolean flag = false;
        try {
            BufferedImage bufreader = ImageIO.read(file);
            int width = bufreader.getWidth();
            int height = bufreader.getHeight();
            if (width == 0 || height == 0) {
                flag = false;
            } else {
                flag = true;
            }
        } catch (IOException e) {
            flag = false;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
    public static final boolean isImageByStream(InputStream inputStream) {
        boolean flag = false;
        try {
            BufferedImage bufreader = ImageIO.read(inputStream);
            int width = bufreader.getWidth();
            int height = bufreader.getHeight();
            if (width == 0 || height == 0) {
                flag = false;
            } else {
                flag = true;
            }
        } catch (IOException e) {
            flag = false;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public final static String getFileHexString(byte[] b) {
        StringBuilder stringBuilder = new StringBuilder();
        if (b == null || b.length <= 0) {
            return null;
        }
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String getFilePath(String fullFileName) {
        String path = fullFileName;
        int n1 = path.lastIndexOf('/');
        int n2 = path.lastIndexOf('\\');
        return (n1 > 0) ? path.substring(0, n1) : path.substring(0, n2);
    }

    public static boolean isExistFilePath(String path) {
        String filePath = getFileFullPath(path);
        File f = new File(filePath);
        return f.isDirectory() && f.exists();
    }

    public static String getFileFullPath(String path) {
        File file = new File(path);
        return (file.isAbsolute()) ? path : file.getAbsolutePath();
    }

    public static void createDirectory(String path) {
        String fullPath = getFileFullPath(path);
        if (!isExistFilePath(fullPath)) {
            File f = new File(getFilePath(fullPath));
            f.mkdirs();
        }
    }

    public static boolean isExistFile(String file) {
        String fullPath = getFileFullPath(file);
        File f = new File(fullPath);
        return f.isFile() && f.exists();
    }

    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        return deleteFileHandle(file);
    }

    private static boolean deleteFileHandle(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                return file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                if (files != null) {
                    for (File item : files) {
                        deleteFileHandle(item);
                    }
                }
            }
            return true;
        } else {
            return false;
        }
    }

}

